import Upload from './upload.model'
import _ from 'lodash';

// const Schema = mongoose.Schema;
// var gfs;
// var conn = mongoose.createConnection(config.mongo.uri);
// gridform.mongo = mongoose.mongo;
// Grid.mongo = mongoose.mongo;

// conn.once('open', function(err) {
//     if(err) return util.handleError(err);

//     gfs = new Grid(conn.db);
//     gridform.db = conn.db;
// });




let multiparty = require('multiparty')
let fs = require('fs')

function handleError(res, err) {
    res.status(500).send(err)
}

exports.create = function(req, res) {
    let form = new multiparty.Form()

    try {
        form.parse(req, (err, fields, files) => {
                if (err) return handleError(res, err)
                console.log(typeof files)
                console.log(files)
                if (_.isEmpty(files)) throw "Files is empty."
                var newUpload = new Upload()
                newUpload.img.data = fs.readFileSync(files.file[0].path)
                newUpload.img.contentType = 'image/png'
                newUpload.save(function (err, doc) {
                    if (err) return handleError(res, err)
                    return res.status(200).json(doc._id)
                })
            })        
    }catch (err) {
       return handleError(res, err)
    }
}


// Get a single file
exports.show = function(req, res, next) {
    Upload.findById(req.params.id, function (err, doc) {
      if (err) return next(err);
      res.contentType(doc.img.contentType);
      res.send(doc.img.data);
    });   
};


exports.load = function(req, res) {
    res.status(200).json({"glossary":"luke"});
};



// exports.create2 = function(req, res) {
//     var form = gridform({db: conn.db, mongo: mongoose.mongo});

//     // optionally store per-file metadata
//     //form.on('fileBegin', function(name, file) {
//     //    file.metadata = {};
//     //});

//     form.parse(req, function(err, fields, files) {
//         if(err) return handleError(res, err);

//         /**
//          * file.name            - the uploaded file name
//          * file.type            - file type per [mime](https://github.com/bentomas/node-mime)
//          * file.size            - uploaded file size (file length in GridFS) named "size" for compatibility
//          * file.path            - same as file.name. included for compatibility
//          * file.lastModified    - included for compatibility
//          * file.root            - the root of the files collection used in MongoDB ('fs' here means the full collection in mongo is named 'fs.files')
//          * file.id              - the ObjectId for this file
//          * @type {file}
//          */
//         var file = files.file;

//         if(_.isNull(file) || _.isUndefined(file))
//             return res.status(400).send('No file');

//         //console.log(file);
//         //console.log(fields);

//         var projectModel = {
//             name: fields.name,
//             info: fields.info,
//             content: fields.content,
//             date: fields.date || new Date(),
//             coverId: file.id
//         };

//         // Thumbnail generation
//         var stream = gfs.createReadStream({_id: file.id});
//         stream.on('error', handleGridStreamErr(res));
//         var img = gm(stream, file.id);
//         img.resize(200, 200, "^");
//         img.crop(200, 200, 0, 0);
//         img.quality(90);
//         img.stream(function(err, outStream) {
//             if(err) return res.status(500).end();
//             else {
//                 var writestream = gfs.createWriteStream({filename: file.name});
//                 writestream.on('close', function(file) {
//                     console.log(file);
//                     projectModel.thumbnailId = file._id;

//                     Upload.create(projectModel, function(err, project) {
//                         if(err) return handleError(res, err);
//                         else return res.status(201).json(project);
//                     });
//                 });
//                 outStream.pipe(writestream);
//             }
//         });

//     });
// };



